package java51.lesson0619;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class BuyXml {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(new File("products.xml"));
			Element root = doc.getRootElement();
			System.out.println("请输入需要购买的商品号：");
			String sch = sc.next();
			System.out.println("请输入需要购买商品的数量：");
			int im = sc.nextInt();
			List<Element> list = doc.selectNodes("/shop/product");
			for (Element e : list) {
				if ((e.selectSingleNode("itemno").getText()).equals(sch)) {

					int ist = Integer.valueOf(e.selectSingleNode("stockcount").getText());
					double eprice = Double.valueOf(e.selectSingleNode("price").getText());
					if (ist >= im) {
						if ((e.attributeValue("discount")).equals("true")) {
							System.out.println("应付金额:" + im * eprice * 0.7 + "元");

						} else {
							System.out.println("应付金额:" + im * eprice + "元");
						}
						int n = ist - im;
						e.selectSingleNode("stockcount").setText(String.valueOf(n));
						OutputFormat format = OutputFormat.createCompactFormat();
						format.setEncoding("utf-8");
						XMLWriter xm = new XMLWriter(new FileOutputStream("products.xml"), format);
						xm.write(doc);
						xm.close();
						return;
					}
					System.out.println("购买数量超过库存量");
					return;
				}
			}
			System.out.println("不存在该编号商品");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
